package com.wy.business.manage.scenery.services;

import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


import oracle.net.aso.p;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Service;

import com.wy.business.manage.scenery.pojos.TCampusSceneryAtlas;
import com.wy.business.manage.scenery.pojos.TCampusSceneryPicture;
import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.exceptions.ServiceException;
import com.wy.framework.services.AbstractBaseService;
import com.wy.component.dataConvert.Base64Image;
import com.wy.component.qrcode.GenerateQRcodeUtil;


@Service
public class CampusSceneryService extends AbstractBaseService {
	private static Logger logger = LoggerFactory
			.getLogger(CampusSceneryService.class);

	@SuppressWarnings("unchecked")
	public List<Map> queryAtlas(int pageIndex,final String atlasName) throws ServiceException {
		// String flag = ServletActionContext.getRequest().getParameter("flag");
		List<Map> result = new ArrayList();
		final int pageSize=10;
		if(pageIndex==0){
			pageIndex=1;
		}
		final int startIndex=(pageIndex - 1) * pageSize;
		//			result = dataBaseDao.queryForList("t_campusscenery_picture.getList");
		result=dataBaseDao.getHibernateTemplate().execute(new HibernateCallback<List>() {
			@Override
			public List doInHibernate(Session session) throws HibernateException {
				if(atlasName.equals("")){
				return session.createQuery("from TCampusSceneryAtlas ta where ta.isavailable=1 ")
                          .setFirstResult(startIndex)
                          .setMaxResults(pageSize)
                          .list();
				}
				else{
					return session.createQuery("from TCampusSceneryAtlas ta where ta.isavailable=1 and ta.atlasname like ?")
                        .setString(0, "%"+atlasName+"%")
                        .setFirstResult(startIndex)
                        .setMaxResults(pageSize)
                        .list();
					
				}
			}
		});
		
		//总记录数
		int rows=queryAtlasCount();
		//总页数
		int currentPage=rows%pageSize==0?rows/pageSize:rows/pageSize+1;
		System.out.println("rows="+rows);
		System.out.println("currentPage="+currentPage);
		Map a=new HashMap();
		a.put("rowCount",rows);
		a.put("currentPage",currentPage);
		result.add(a);
		return result;
	}
	
	public int queryAtlasCount(){
		List list=dataBaseDao.getHibernateTemplate().find("from TCampusSceneryAtlas",null);
		if(list==null || list.size()==0){
			return 0;
		}
		else{
			return list.size();
		}
	}
	
	
	/**
	 * Function Name               addAtlas                                   
	 * @throws ErrorSqlException          		             
	 * @description TODO(校园风光-添加图集)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-24 上午11:29:56           朱仕稳                    Initial
	 **********************************************************************
	 */
	public void addAtlas() throws ErrorSqlException{
		String atlasname=ServletActionContext.getRequest().getParameter("atlasname");
		TCampusSceneryAtlas tCampusSceneryAtlas=new TCampusSceneryAtlas();
		tCampusSceneryAtlas.setAtlasid(UUID.randomUUID().toString());
		tCampusSceneryAtlas.setAtlasname(atlasname);
		tCampusSceneryAtlas.setIsavailable("1");
		tCampusSceneryAtlas.setAlbumname(tCampusSceneryAtlas.getAlbumname());
		tCampusSceneryAtlas.setCreattime(new Timestamp(System.currentTimeMillis()));
		tCampusSceneryAtlas.setUpdatetime(new Timestamp(System.currentTimeMillis()));
		dataBaseDao.save(tCampusSceneryAtlas);
	}

	/**
	 * Function Name               modifyAtlas                                             		             
	 * @description TODO(校园风光-修改图集)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-24 上午11:30:15           朱仕稳                    Initial
	 **********************************************************************
	 */
	public void modifyAtlas(TCampusSceneryAtlas tCampusSceneryAtlas) {
		tCampusSceneryAtlas.setUpdatetime(new Timestamp(System.currentTimeMillis()));
		this.dataBaseDao.getHibernateTemplate().update(tCampusSceneryAtlas);
	}

	/**
	 * Function Name               removeAtlas                                             		             
	 * @throws ErrorSqlException 
	 * @description TODO(校园风光-删除图集)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-24 下午1:41:09           朱仕稳                    Initial
	 **********************************************************************
	 */
	public void removeAtlas(TCampusSceneryAtlas tCampusSceneryAtlas) throws ErrorSqlException {
		tCampusSceneryAtlas.setIsavailable("0");//修改数据为无效
		tCampusSceneryAtlas.setUpdatetime(new Timestamp(System.currentTimeMillis()));
		this.dataBaseDao.update(tCampusSceneryAtlas);
	}

	
	/**
	 * Function Name               queryPicture                                   
	 * @return          		             
	 * @throws ErrorSqlException 
	 * @description TODO(校园风光-查询图片)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-24 下午5:06:25           朱仕稳                    Initial
	 **********************************************************************
	 */
	@SuppressWarnings("unchecked")
	public List<Map> queryPicture(String atlasIds) throws ErrorSqlException {
		
		
			return dataBaseDao.queryForList("t_campusscenery_picture.queryPictureList",atlasIds);
			
				
	}
	
	@SuppressWarnings("unchecked")
	public List<Map> searchPicture(String pictureNames) throws ErrorSqlException {
		
		
			return dataBaseDao.queryForList("t_campusscenery_picture.searchPictureList","%"+pictureNames+"%");
			
				
	}
	/**
	 * Function Name               removePicture                                   
	 * @param tCampusSceneryPicture
	 * @throws ErrorSqlException          		             
	 * @description TODO(删除校园风光-校园图片)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-25 上午9:47:43           朱仕稳                    Initial
	 **********************************************************************
	 */
	public void removePicture(TCampusSceneryPicture tCampusSceneryPicture) throws ErrorSqlException {
		tCampusSceneryPicture.setIsavailable("0");//修改数据为无效
		tCampusSceneryPicture.setUpdatetime(new Timestamp(System.currentTimeMillis()));
		this.dataBaseDao.getHibernateTemplate().update(tCampusSceneryPicture);
	}
	
	
	/**
	 * Function Name               addPicture                                   
	 * @param tCampusSceneryPicture
	 * @throws ErrorSqlException          		             
	 * @throws URISyntaxException 
	 * @description TODO(校园风光-添加图片)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-25 上午9:51:12           朱仕稳                    Initial
	 **********************************************************************
	 */
	@SuppressWarnings("unchecked")
	public void addPicture(String atlasIds,String pictureUrls,String pictureNames) throws ErrorSqlException, URISyntaxException {
		
		String[] urls=pictureUrls.split("#");
		String[] ids=atlasIds.split(",");
		String[] names=pictureNames.split(",");
		for(int i=0;i<urls.length;i++){
			TCampusSceneryPicture tCampusSceneryPicture=new TCampusSceneryPicture();
			String picId=UUID.randomUUID().toString();
			tCampusSceneryPicture.setPictureid(picId);
			String rootPath = GenerateQRcodeUtil.class.getClassLoader().getResource("").toURI().getPath();
			String logoPath=rootPath.replace("WEB-INF/classes/", "")+"resources/img/scenery/"+picId+".png";
			Base64Image.GenerateImage(urls[i], logoPath);
			tCampusSceneryPicture.setPictureurl("../../resources/img/scenery/"+picId+".png");
			tCampusSceneryPicture.setPicturename(names[i]);
			TCampusSceneryAtlas atlas=(TCampusSceneryAtlas) dataBaseDao.load(TCampusSceneryAtlas.class,ids[i]);
			tCampusSceneryPicture.setAtlas(atlas);
			tCampusSceneryPicture.setAuditstatus("1");//审核状态,0:未审核,1:通过,2:拒绝
			tCampusSceneryPicture.setCreattime(new Timestamp(System.currentTimeMillis()));
			tCampusSceneryPicture.setUpdatetime(new Timestamp(System.currentTimeMillis()));
			tCampusSceneryPicture.setIsavailable("1");
	     	this.dataBaseDao.save(tCampusSceneryPicture);
		}
	}

	
	/**
	 * Function Name               queryPictureById                                   
	 * @return
	 * @throws ErrorSqlException          		             
	 * @description TODO(根据图片Id查询图片信息)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-25 上午10:43:23           朱仕稳                    Initial
	 **********************************************************************
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Map> queryPictureById() throws ErrorSqlException {
		String picId=ServletActionContext.getRequest().getParameter("picId");
		return this.dataBaseDao.queryForList("t_campusscenery_picture.queryPictureById", picId);
	}
	
	
	/**
	 * Function Name               queryAtlas                                   
	 * @return          		             
	 * @throws ErrorSqlException 
	 * @description TODO(查询所有图集信息)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-25 上午11:13:45           朱仕稳                    Initial
	 **********************************************************************
	 */
	@SuppressWarnings("unchecked")
	public List<Map> queryAtlas() throws ErrorSqlException{
		return this.dataBaseDao.queryForList("t_campusscenery_atlas.queryAtlas");
		
	}

	
	/**
	 * Function Name               modifyPicture                                   
	 * @param picture          		             
	 * @throws ErrorSqlException 
	 * @description TODO(校园风光-修改图片信息)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-3-25 上午11:37:26           朱仕稳                    Initial
	 **********************************************************************
	 */
	@SuppressWarnings("unchecked")
	public void modifyPicture(TCampusSceneryPicture picture) throws ErrorSqlException {
		List params=new ArrayList();
		params.add(picture.getPicturename());
		params.add(new Timestamp(System.currentTimeMillis()));
		params.add(picture.getDescribe());
		params.add(picture.getAtlas().getAtlasid());
		params.add(picture.getAuditstatus());
		params.add(picture.getPictureid());
		this.dataBaseDao.update("t_campusscenery_picture.updateForPicture",params);
	}
}


